package com.mysiteforme.admin.util;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.*;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.OSSObject;
import com.aliyun.oss.model.ObjectMetadata;
import com.aliyun.oss.model.PutObjectResult;
import com.baomidou.mybatisplus.toolkit.StringUtils;
import org.springframework.web.multipart.MultipartFile;


/**
 * OSS工具类
 * 
 * @author Maxwell
 *
 */
public class OSSUtils {

	private static final Logger logger = LoggerFactory.getLogger(OSSUtils.class);

	/**
	 * 上传通过File, 返回代码,结果,保存路径
	 * 
	 * @param file
	 * @param directory
	 * @param postfix
	 * @return
	 * @throws Exception 
	 */
	public static Map<String,Object> uploadByFile(File file, String directory, String postfix) throws Exception {
		Map<String,Object> outDto = new HashMap<String,Object>();
		byte[] buffer = null;
		try {
			// 连接oss
			Map<String,Object> dataDto = initOSS();
			if (dataDto == null) {
				outDto.put("code","-1");
				return outDto;
			}
			FileInputStream fis = new FileInputStream(file);
			ByteArrayOutputStream bos = new ByteArrayOutputStream(1000);
			byte[] b = new byte[1000];
			int n;
			while ((n = fis.read(b)) != -1) {
				bos.write(b, 0, n);
			}
			fis.close();
			bos.close();
			buffer = bos.toByteArray();
			// 在oss存储中的mpbw（文件夹）下，保存某个文档到这个地方，文件名称为uuid
			String uuid = UUID.randomUUID().toString().replace("-", "") + "." + postfix;
			String skey = directory + uuid;
			OSSClient ossClient = (OSSClient) dataDto.get("ossclient");
			PutObjectResult putResult = ossClient.putObject(dataDto.get("bucket").toString(), skey,
					new ByteArrayInputStream(buffer));
			ossClient.shutdown();
			ossClient = null;
			outDto.put("code","1");
			// 解析结果
			outDto.put("path",
					dataDto.get("endpoint") + "/" + directory + uuid);
			outDto.put("key", skey);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return outDto;
	}

	/**
	 *
	 * @param file
	 * @return
	 * @throws Exception
	 */
	public String uploadImg2Oss(MultipartFile file) throws Exception {
		if (file.getSize() > 10 * 1024 * 1024) {
			throw new Exception("上传图片大小不能超过10M！");
		}

		String originalFilename = file.getOriginalFilename();
		System.out.println(originalFilename);
		String substring = originalFilename.substring(originalFilename.lastIndexOf(".")+1).toLowerCase();

		try {
			InputStream inputStream = file.getInputStream();
			//System.out.println("文件名称="+name);
			Map map = this.uploadByInputStream(inputStream, substring,Constants.PIC_PATH_BANNER);
			return map.get("path").toString();
		} catch (Exception e) {
			throw new Exception("图片上传失败2");
		}
	}
	/**
	 * 上传通过InputStream, 返回代码,结果,保存路径
	 * 
	 * @param is
	 * @param postfix
	 * @param diskName
	 * @return
	 * @throws Exception 
	 */
	public static Map<String,Object> uploadByInputStream(InputStream is, String postfix, String diskName) throws Exception {
		Map<String,Object> outDto = new HashMap<String,Object>();
		try {
			// 连接oss
			Map<String,Object> dataDto = initOSS();
			if (dataDto == null) {
				outDto.put("code","-1");
				return outDto;
			}
			// 在oss存储中的mpbw（文件夹）下，保存某个文档到这个地方，文件名称为uuid
			String uuid = UUID.randomUUID().toString().replace("-", "") + "." + postfix;
			int fileSize = is.available();
			// 创建上传Object的Metadata
			ObjectMetadata metadata = new ObjectMetadata();
			metadata.setContentLength(is.available());
			metadata.setCacheControl("no-cache");
			metadata.setHeader("Pragma", "no-cache");
			metadata.setContentEncoding("utf-8");
			metadata.setContentType(getContentType(uuid));
			metadata.setContentDisposition("filename/filesize=" + uuid + "/" + fileSize + "Byte.");
			String skey =  diskName + uuid;
			OSSClient ossClient = (OSSClient) dataDto.get("ossclient");
			PutObjectResult putResult = ossClient.putObject(dataDto.get("bucket").toString(), skey, is, metadata);
			ossClient.shutdown();
			ossClient = null;
			outDto.put("code","1");
			// 解析结果
			outDto.put("path", dataDto.get("endpoint") + "/" + diskName + uuid);
			outDto.put("key", skey);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return outDto;
	}
	
	/**
	 * 上传通过InputStream, 返回代码,结果,保存路径
	 * 
	 * @param is
	 * @param postfix
	 * @param diskName
	 * @return
	 * @throws Exception 
	 */
	public static Map<String,Object> uploadByInputStream2(String fileName,InputStream is, String postfix, String diskName) throws Exception {
		Map<String,Object> outDto = new HashMap<String,Object>();
		try {
			// 连接oss
			Map<String,Object> dataDto = initOSS();
			if (dataDto == null) {
				outDto.put("code","-1");
				return outDto;
			}
			// 在oss存储中的mpbw（文件夹）下，保存某个文档到这个地方，文件名称为uuid
			String add = fileName.substring(fileName.lastIndexOf("."));
			String uuid =fileName.substring(0, fileName.lastIndexOf("."));
			Date date = new Date();
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			String dateString = sdf.format(date);
			uuid = uuid + dateString+add;
			int fileSize = is.available();
			// 创建上传Object的Metadata
			ObjectMetadata metadata = new ObjectMetadata();
			metadata.setContentLength(is.available());
			metadata.setCacheControl("no-cache");
			metadata.setHeader("Pragma", "no-cache");
			metadata.setContentEncoding("utf-8");
			metadata.setContentType(getContentType(uuid));
			metadata.setContentDisposition("filename/filesize=" + uuid + "/" + fileSize + "Byte.");
			String skey = diskName + uuid;
			OSSClient ossClient = (OSSClient) dataDto.get("ossclient");
			PutObjectResult putResult = ossClient.putObject(dataDto.get("bucket").toString(), skey, is, metadata);
			ossClient.shutdown();
			ossClient = null;
			outDto.put("code","1");
			// 解析结果
			outDto.put("path",
					dataDto.get("endpoint") + "/" + diskName + uuid);
			outDto.put("key", skey);
			outDto.put("fileName", uuid);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return outDto;
	}

	/**
	 * 获取oss上某个文件的输入流
	 * 
	 * @param key
	 * @return
	 * @throws Exception
	 */
	public static InputStream getOssFileIS(String key) throws Exception {
		try {
			// 连接oss
			Map<String,Object> dataDto = initOSS();
			if (dataDto == null) {
				return null;
			}
			OSSClient ossClient = (OSSClient) dataDto.get("ossclient");
			OSSObject ossObject = ossClient.getObject(dataDto.get("bucket").toString(), key);
			InputStream in = ossObject.getObjectContent();
			return in;
		} catch (Exception ex) {
			ex.printStackTrace();
			return null;
		}
	}

	/**
	 * 从输入流中获取字节数组
	 * 
	 * @param inputStream
	 * @return
	 * @throws IOException
	 */
	public static byte[] readInputStream(InputStream inputStream) throws IOException {
		byte[] buffer = new byte[1024];
		int len = 0;
		ByteArrayOutputStream bos = new ByteArrayOutputStream();
		while ((len = inputStream.read(buffer)) != -1) {
			bos.write(buffer, 0, len);
		}
		bos.close();
		return bos.toByteArray();
	}

	/**
	 * 删除文档
	 * 
	 * @param key
	 * @return
	 * @throws Exception
	 */
	public static Map<String,Object> deleteByKey(String key) throws Exception {
		Map<String,Object> outDto = new HashMap<String,Object>();
		try {
			// 连接oss
			Map<String,Object> dataDto = initOSS();
			if (dataDto == null) {
				outDto.put("code","-1");
				return dataDto;
			}
			OSSClient ossClient = (OSSClient) dataDto.get("ossclient");
			// 校验OSS是否存在文档
			boolean flag = ossClient.doesObjectExist(dataDto.get("bucket").toString(), key);
			if (flag) {
				// 如果有，那么删除
				ossClient.deleteObject(dataDto.get("bucket").toString(), key);
			}
			ossClient.shutdown();
			ossClient = null;
			outDto.put("code","1");
			return dataDto;
		} catch (Exception ex) {
			ex.printStackTrace();
			return null;
		}
	}

	/**
	 * 初始化OSS连接
	 */
	private static Map<String,Object> initOSS() {
		Map<String,Object> outDto = new HashMap<String,Object>();
		try {
			OSSClient ossClient = new OSSClient("http://oss-cn-beijing.aliyuncs.com", "LTAI4FvQfZZaGRvaru165GG2",
					"HK6XZ6jOkhhjaMCJssT5c2oZJRKBCw");
			outDto.put("ossclient", ossClient);
			outDto.put("osspath", "http://oss-cn-beijing.aliyuncs.com");
			outDto.put("bucket", "sxlc-ydyl");
			outDto.put("endpoint", "http://sxlc-ydyl.oss-cn-beijing.aliyuncs.com");
//			OSSClient ossClient = new OSSClient("http://osjygl-vpc2-jyglsj.oss02-cn-beijing-sinopec-d01-a.yun-inc.sinopec.com", "z3YCxa8juv166mBb",
//					"n36N3zbYbaBp3OnCdJvYG1x32nfXFa");
//			outDto.put("ossclient", ossClient);
//			outDto.put("osspath", "http://oss03.aliyun.sinopec.com");
//			outDto.put("bucket", "osjygl-vpc2-jyglsj");
//			outDto.put("endpoint", "http://osjygl-vpc2-jyglsj.oss02-cn-beijing-sinopec-d01-a.yun-inc.sinopec.com");
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
		return outDto;
	}

	/**
	 * 通过文件名判断并获取OSS服务文件上传时文件的contentType
	 * 
	 * @param fileName
	 *            文件名
	 * @return 文件的contentType
	 */
	private static final String getContentType(String fileName) {
		String fileExtension = fileName.substring(fileName.lastIndexOf(".") + 1);
		if ("bmp".equalsIgnoreCase(fileExtension))
			return "image/bmp";
		if ("gif".equalsIgnoreCase(fileExtension))
			return "image/gif";
		if ("jpeg".equalsIgnoreCase(fileExtension) || "jpg".equalsIgnoreCase(fileExtension)
				|| "png".equalsIgnoreCase(fileExtension))
			return "image/jpeg";
		if ("html".equalsIgnoreCase(fileExtension))
			return "text/html";
		if ("txt".equalsIgnoreCase(fileExtension))
			return "text/plain";
		if ("vsd".equalsIgnoreCase(fileExtension))
			return "application/vnd.visio";
		if ("ppt".equalsIgnoreCase(fileExtension) || "pptx".equalsIgnoreCase(fileExtension))
			return "application/vnd.ms-powerpoint";
		if ("doc".equalsIgnoreCase(fileExtension) || "docx".equalsIgnoreCase(fileExtension))
			return "application/msword";
		if ("xml".equalsIgnoreCase(fileExtension))
			return "text/xml";
		if ("pdf".equalsIgnoreCase(fileExtension))
			return "application/pdf";
		if("mp4".equalsIgnoreCase(fileExtension))
			return "video/mp4";
		return "text/html";
	}
	
	/**
	 * @Title: download
	 * @Description: 下载
	 * @param @param
	 *            key
	 * @param @return
	 * @param @throws
	 *            Exception
	 * @return FileObject
	 * @throws @author
	 */
	/*public static FileObject download(String key) throws Exception {
		OSSClient ossClient = initOSS();
		OSSObject ossObject = ossClient.getObject(CommonUtil.getProperty("OSS.BUCKET"), key);
		InputStream in = ossObject.getObjectContent();
		ByteArrayOutputStream swapStream = new ByteArrayOutputStream();
		byte[] buff = new byte[1024];
		int rc = 0;
		while ((rc = in.read(buff, 0, 1024)) > 0) {
			swapStream.write(buff, 0, rc);
		}
		byte[] in2b = swapStream.toByteArray();
		FileObject obj = new FileObject();
		obj.setFileContent(in2b);
		ossClient.shutdown();
		return obj;

	}
	*/
	
	/**
	 * @Title: download
	 * @Description: 下载
	 * @param @param
	 *            key
	 * @param @return
	 * @param @throws
	 *            Exception
	 * @return FileObject
	 * @throws @author
	 */
	public static void download(String key) throws Exception {
		InputStream in = getOssFileIS(key);
		ByteArrayOutputStream swapStream = new ByteArrayOutputStream();
		byte[] buff = new byte[1024];
		int rc = 0;
		while ((rc = in.read(buff, 0, 1024)) > 0) {
			swapStream.write(buff, 0, rc);
		}
		byte[] in2b = swapStream.toByteArray();

	}

/****
 * oss 删除
 * @param str
 * @return
 */
public static RestResponse delete(String str){
	if(StringUtils.isEmpty(str)){
		return RestResponse.failure("删除路径不能为空");
	}
	/**或者这种裁剪方式*   /str=str.replace("http://z5326383.oss-cn-qingdao.aliyuncs.com/","")*/
	int begin=str.indexOf("CLYJ");
	int last=str.length();
	str=str.substring(begin,last);
	System.out.println();
	Map<String,Object> dataDto = initOSS();
	if (dataDto == null) {
		return RestResponse.failure("OSS连接异常");
	}
	OSSClient ossClient = (OSSClient) dataDto.get("ossclient");
	// 校验OSS是否存在文档
	boolean flag = ossClient.doesObjectExist(dataDto.get("bucket").toString(), str);
	if (!flag) {
		return RestResponse.failure("服务器无此路径");
	}else{
		// 如果有，那么删除
		ossClient.deleteObject(dataDto.get("bucket").toString(), str);
	}
	ossClient.shutdown();
	ossClient = null;
	return RestResponse.success();
	
}

public static void test(){
		System.out.print("23312312321312");
}
	public static void main(String args[]) {
		Map<String,Object> outDto = new HashMap<String,Object>();
		String filename="F:\\workspace\\ssh_photo\\WebContent\\uploadFile\\1444783552338pic.jpg";
		int begin=filename.indexOf("ssh_photo");
		int last=filename.length();
		System.out.println(filename.substring(begin,last));
		
	}
	

	}
	
